﻿using AutoMapper;
using BackData;
using Details.API.Application.Command.Goods;
using Details.API.DTOs;
using Domain;
using Infratructure.RepositoryWay;
using MediatR;

namespace Details.API.Application.Handler.Goods
{
    /// <summary>
    /// 商品列表
    /// </summary>
    public class GetGoodsHandler:IRequestHandler<GetGoodsCommand, APIPaging<GoodsDTO>>
    {
        private readonly IRepository<GoodsModel> goodway;
        private readonly ILogger<GetGoodsHandler> log;
        private readonly IMapper mapper;

        public GetGoodsHandler(IRepository<GoodsModel> goodway, ILogger<GetGoodsHandler> log, IMapper mapper)
        {
            this.goodway = goodway;
            this.log = log;
            this.mapper = mapper;
        }

        /// <summary>
        /// 商品列表
        /// </summary>
        /// <param name="request">参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<APIPaging<GoodsDTO>> Handle(GetGoodsCommand request, CancellationToken cancellationToken)
        {
            var res = new APIPaging<GoodsDTO>();
            var value = goodway.GetAll().Where(x => x.IsDel == false).ToList(); //执行查询,预执行无法映射
            if(value.Any())
            {
                //查询条件可后续添加
                var result = mapper.Map<List<GoodsDTO>>(value); //映射DTO
                res.Message = "获取商品列表成功";
                //  log.LogInformation($"{DateTime.UtcNow}获取商品列表成功");  // 日志,列表日志太多就先不记录

                res.Totalcount = result.Count;
                res.Code = StateCode.OK;
                res.PageData = result.OrderByDescending(x => x.Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();    //分页   
                return Task.FromResult(res);
            }
            else
            {
                res.Message = "暂无数据";
                res.Code = StateCode.Fail;
                return Task.FromResult(res);
            }


        }
    }
}
